package com.eascs.web.o2o.web.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eascs.app.dao.PageResult;
import com.eascs.app.exception.ControllerException;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.view.ViewContext;
import com.eascs.tag.MenuTag;
import com.eascs.web.o2o.web.common.BaseMasterViewController;
import com.eascs.web.o2o.web.form.ChannelBusStatisForm;
import com.eascs.web.o2o.web.form.RecommendStaticForm;
import com.eascs.web.o2o.web.service.BuildExcelService;
import com.eascs.web.o2o.web.service.RecommendStaticService;
import com.eascs.web.o2o.web.util.BankRowWriteHandler;
//beizhu
@Controller
@RequestMapping("/reconmmend")
public class RecommendStaticController extends BaseMasterViewController {

	@Override
	public void preHandle() {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "reconmmend");
	}

	@Autowired
	RecommendStaticService recommendStaticService;

	@RequestMapping("/index")
	public String index(ChannelBusStatisForm entity) {

		String o2ourl = "/restRecommend/o2o";

		if (entity != null) {
			String billCode = entity.getBillCode() == null ? "" : entity.getBillCode();
			String loanType = entity.getLoanType() == null ? "" : entity.getLoanType();
			String partnerName = entity.getPartnerName() == null ? "" : entity.getPartnerName();
			String partnerType = entity.getPartnerType() == null ? "" : entity.getPartnerType();
			String loanerName = entity.getLoanerName() == null ? "" : entity.getLoanerName();
			String loanDate = entity.getLoanDate()== null ? "" : entity.getLoanDate();
			String loanDateEnd = entity.getLoanDateEnd()== null ? "" : entity.getLoanDateEnd();
			o2ourl = UrlUtil.appendUrl(o2ourl, "billCode", billCode);
			o2ourl = UrlUtil.appendUrl(o2ourl, "loanType", loanType);
			o2ourl = UrlUtil.appendUrl(o2ourl, "partnerName", partnerName);
			o2ourl = UrlUtil.appendUrl(o2ourl, "partnerType", partnerType);
			o2ourl = UrlUtil.appendUrl(o2ourl, "loanerName", loanerName);
			o2ourl = UrlUtil.appendUrl(o2ourl, "loanDate", loanDate);
			o2ourl = UrlUtil.appendUrl(o2ourl, "loanDateEnd", loanDateEnd);
			o2ourl = o2ourl + "&pageIndex=";
		} else {
			o2ourl = o2ourl + "?pageIndex=";
		}
		ViewContext.put("o2ourl", o2ourl);
		ViewContext.put("vo", entity);
		return "report/recommend";
	}

	@RequestMapping("/download")
	public void downloadTeam(ChannelBusStatisForm entity, HttpServletResponse httpServletResponse,
			HttpServletRequest request) {
		entity.setPageSize(Integer.MAX_VALUE);
		PageResult<Object[]> pageResult = recommendStaticService.getRecommendStaticByPage(entity);
		saveReport(pageResult.getData());
		String path = ProvinceTeamTotalController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/recommend_file.xls").toString();
		OutputStream os = null;
		try {
			String outfile;
				outfile = "贷款单推荐统计.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}

	// 先生成文件然后在读这个文件(省区查询报表)
	public String saveReport(List<Object[]> data) {
		// 模板
		String soucreFileName = "/excelTemplate/recommend.xls";
		// 输出路径
		StringBuffer s = new StringBuffer();
		String path = ProvinceTeamTotalController.class.getResource("/excelTemplate").getPath();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

		String outPath = s.append(path).append("/recommend_file.xls").toString();

		// 包含的列
		int col = 13;
		// 需要统计的列
		int[] arr = {3};
		String title;

		title = "贷款单推荐统计";

		// 开始的表格，行，列
		int sheetIndex = 0;
		int rowIndex = 2;
		int columnIndex = 0;
		BankRowWriteHandler bankRowWriteHandler = new BankRowWriteHandler(data, col, arr, Arrays.asList(title),
				sheetIndex, rowIndex, columnIndex);

		// 生产excel
		write(soucreFileName, outPath, bankRowWriteHandler);

		return path + "/" + outPath;
	}

	/*
	 * 生成excel 参数：数据，源文件，输出文件，excel包含的列，需要统计的列，excel标题
	 */
	public void write(String soucreFileName, String outPath, BankRowWriteHandler bankRowWriteHandler) {
		IoUtil.createDirectorieIfMissing(new File(outPath).getParentFile());
		try {
			ExcelApiHelper.writeHandle(new FileOutputStream(outPath),
					BuildExcelService.class.getResourceAsStream(soucreFileName), bankRowWriteHandler);

		} catch (Exception e) {
			throw new ControllerException(e);
		}
	}

}
